package br.indt.framework.utils;

import javax.microedition.lcdui.Image;

public class ImageUtils {

	// copied from
	// http://www.developer.nokia.com/Community/Discussion/showthread.php?173266-PNG-Image-Resize#post613559
	public static Image resizeImage(Image temp, int wd, int ht) {
		
		if (temp.getWidth() != wd || temp.getHeight() != ht) {
		
			// Need an array (for RGB, with the size of original image)
			int rgb[] = new int[temp.getWidth() * temp.getHeight()];
			// Get the RGB array of image into "rgb"
			temp.getRGB(rgb, 0, temp.getWidth(), 0, 0, temp.getWidth(), temp.getHeight());
			// Call to our function and obtain RGB2
			int rgb2[] = reescalaArray(rgb, temp.getWidth(), temp.getHeight(), wd, ht);
			// Create an image with that RGB array
			return Image.createRGBImage(rgb2, wd, ht, true);
			
		}
		
		return temp;
	}

	private static int[] reescalaArray(int[] ini, int x, int y, int x2, int y2) {
		int out[] = new int[x2 * y2];
		for (int yy = 0; yy < y2; yy++) {
			int dy = yy * y / y2;
			for (int xx = 0; xx < x2; xx++) {
				int dx = xx * x / x2;
				out[(x2 * yy) + xx] = ini[(x * dy) + dx];
			}
		}
		return out;
	}

	public static Image cropImage(Image image, int x, int y, int widht, int height, int transform) {
		return Image.createImage(image, x, y, widht, height, transform);
	}
	
	public static Image blend(Image img, int opacity) {
		int rgbdata[] = new int[img.getWidth() * img.getHeight()];
		img.getRGB(rgbdata, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());
		for (int i = 0; i < rgbdata.length; i++) {
			int pixel = rgbdata[i];
			
			// get the rgb data of the pixel by masking the bits using & bitwise operator
			int r = ((pixel & 0x00ff0000) >> 16);
			int g = ((pixel & 0x0000ff00) >> 8);
			int b = ((pixel & 0x000000ff) >> 0); 

			// rearrange the pixel using its previous color channel values.
			// we will only modify the alpha.
			rgbdata[i] = (opacity << 24) + (r << 16) + (g << 8) + b;	
		}
		
		return Image.createRGBImage(rgbdata, img.getWidth(), img.getHeight(), true);
	}
}
